<?php


namespace app\home\controller;


use app\base\BaseController;
use app\home\model\ProductionPlanDetail;
use think\Exception;
use think\facade\Db;
use think\facade\View;

/**
 * Class ProductionPlan
 * @package app\home\controller
 * 生产计划
 */
class ProductionPlan extends BaseController
{
    protected $table='production_plan';
    protected $table_detail='production_plan_detail';
    protected $title='生产计划';
    private $sessionKey='pageProductionPlan';

    /**
     * date:2024/3/21
     * 列表
     */
    public function index()
    {
        $param=$this->param;
        if (request()->isAjax()) {

            $where[]=['status','>',-1];
            if (isset($param['status'])&&$param['status']){
                $where[]=['status','=',$param['status']];
            }
            if (isset($param['id'])&&$param['id']){
                $where[]=['id','=',$param['id']];
            }
            if (isset($param['printCode'])&&$param['printCode']){
                $where[]=['printCode','=',$param['printCode']];
            }

            foreach (['bar_code','mdName','specs'] as $i){
                if (isset($param[$i])&&$param[$i]){
                    $where[]=[$i,'like','%'.$param[$i].'%'];
                }
            }
            if (isset($param['orderDate'])&&$param['orderDate']){
                $times=explode('~',$param['orderDate']);
                $where[]=['orderDate','between',$times];
            }
            if (isset($param['planDate'])&&$param['planDate']){
                $pTimes=explode('~',$param['planDate']);
                $where[]=['planned_time','between',$pTimes];
            }
            session($this->sessionKey,$where);
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name('production_plan_view')
                ->where($where)
                ->field("*,
                (select sum(qualifiedNum) from fy_process_reporting  pr where pr.correlation_order=1 and pr.material_dossier_id=fy_production_plan_view.material_dossier_id and pr.status=3 and pr.is_end=1)qualifiedNum")
                ->order('production_plan_id desc')
                ->paginate($rows)->each(function ($item,$index){
                    $item['qualifiedNum']= $item['qualifiedNum']??0;
                    $item['c_rate']=number_format(($item['qualifiedNum']/$item['num'])*100,2);
                    return $item;
                });
            return table_assign(0, '', $list);
        } else {
            return view();
        }

    }
    /**
     * @return \json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * date:2024/3/21
     * 添加
     */
    public function add()
    {
        $param = get_params();
        if (request()->isAjax()) {
            $info=[];

            $postData=$this->param;
            if ($param['id']>0){
                $info=Db::name($this->table)->where('id',$postData['id'])->find();
            }
            $mxid=$postData['mxid']??[];
            $material_id=$postData['material_id']??[];
            $num=$postData['num']??[];
            $planned_time=$postData['planned_time']??[];
            $bom_id=$postData['bom_id']??[];
            $craft_route_id=$postData['craft_route_id']??[];
            $ycl_material_dossier_id=$postData['ycl_material_dossier_id']??[];
            $ycl_yjNum=$postData['ycl_yjNum']??[];
            $ycl_ckNum=$postData['ycl_ckNum']??[];
            $chaque=$postData['chaque']??[];
            $wId=$postData['wId']??[];
            $kcNum=$postData['kcNum']??[];
            $param=[
                'remark'=>$postData['remark'],
                'orderDate'=>$postData['orderDate'],
                'status'=>$postData['status'],
                'id'=>$postData['id']??0,
            ];
            if (!$material_id||!$num||!$planned_time){
                return to_assign(1,'参数缺失');
            }
            if ($info&&$info['status']==2){
                if (!$ycl_material_dossier_id||!$ycl_yjNum||!$ycl_ckNum){
                    return to_assign(1,'参数缺失');
                }
            }
            Db::startTrans();
            $param['update_time']=time();
            $id=$param['id']??0;
            try {
                if ($param['id'] > 0) {
                    Db::name($this->table)->strict(false)->field(true)->update($param);
                    add_log('edit', $param['id'], $postData,$this->title);
                } else {
                    $param['create_time'] = time();
                    $param['orderNum'] = orderNum('JHH');
                    $id = Db::name($this->table)->strict(false)->field(true)->insertGetId($param);
                    add_log('add', $id, $postData,$this->title);
                }
                if (!$info||$info['status']==1){
                    foreach ($material_id as $k=>$v){
                        if (empty($num[$k])||empty($planned_time[$k])||empty($bom_id[$k])){
                            throw new Exception('参数有误');
                        }
                        $mxData=[
                            'production_plan_id'=>$id,
                            'material_dossier_id'=>$material_id[$k],
                            'num'=>$num[$k],
                            'planned_time'=>$planned_time[$k],
                            'bom_id'=>$bom_id[$k],
                            'craft_route_id'=>$craft_route_id[$k]??0,
                            'create_time'=>time(),
                            'update_time'=>time()
                        ];
                        if (isset($mxid[$k])&&$mxid[$k]){
                            $mxData['id']=$mxid[$k];
                        }
                        Db::name('production_plan_detail')->save($mxData);
                    }
                }

                if ($info&&$info['status']==2){
                    Db::name('production_plan_ycl')->where('deleted',0)
                        ->where('production_plan_id',$id)
                        ->update(['status'=>-1,'deleted'=>time(),'update_time'=>time()]);
                    $yclData=[];
                    foreach ($ycl_material_dossier_id as $y=>$ymd){
                        if (empty($ycl_ckNum[$y])||!isset($ycl_ckNum[$y])){
                            throw new Exception('出库数量不能为空');
                        }
                        $yclData[]=[
                            'production_plan_id'=>$id,
                            'material_dossier_id'=>$ymd,
                            'yjNum'=>$ycl_yjNum[$y]??0,
                            'ckNum'=>$ycl_ckNum[$y]??0,
                            'chaque'=>$chaque[$y]??0,
                            'wId'=>$wId[$y]??1,
                            'kcNum'=>$kcNum[$y]??0,
                            'create_time'=>time(),
                            'update_time'=>time()
                        ];
                    }
                    Db::name('production_plan_ycl')->insertAll($yclData);
                }

                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }

            return to_assign();
        } else {
            $id = isset($param['id']) ? $param['id'] : 0;
            if ($id > 0) {
                $detail = Db::name($this->table)->where('id', $id)->field("*,(select name from fy_admin a where a.id=makeUser)username")->find();

                $mxList=ProductionPlanDetail::alias('ppd')
                    ->with(['craftRoute','bom'])
                    ->where('ppd.status','1')->where('ppd.production_plan_id',$id)
                    ->join('material_dossier md','md.id=ppd.material_dossier_id','left')
                    ->field("ppd.*,md.name as mdName,md.bar_code,md.specs,md.unit")
                    ->select();
                View::assign('mxList', $mxList);
                $yclList= Db::name('production_plan_ycl')->alias('ppy')
                    ->where('ppy.deleted',0)
                    ->where('ppy.status','>',-1)
                    ->leftJoin('material_dossier md1','md1.id=ppy.material_dossier_id ')
                    ->where('ppy.production_plan_id',$id)
                    ->leftJoin('material_kucun_view mkv','mkv.mdId=ppy.material_dossier_id and mkv.wId=ppy.wId')
                    ->field("ppy.*,mkv.mdId,mkv.bar_code,mkv.mdName,mkv.specs,mkv.unit,mkv.countNum,mkv.sendNum")
                    ->select()
//                    ->each(function ($item){
//                        $item['kcNum']=$item['countNum']-$item['sendNum'];
//                        $item['chaque']=($item['yjNum']-$item['kcNum'])<0?0:$item['yjNum']-$item['kcNum'];
//                        return $item;
//                    })
                    ->toArray();


                View::assign('yclList', $yclList);
            }else{
                $detail=[];
            }
            $warehouse=Db::name('warehouse')->where('status','1')
                ->where('deleted',0)->field('id,name')->select();

            View::assign('detail', $detail);
            View::assign('warehouse', $warehouse);
            View::assign('id', $id);
            View::assign('defalutTime', date('Y-m-d'));
            return view('form');
        }
    }

    public function addMx()
    {
        if (request()->isPost()) {
            $where[]=['status','=',1];
            $limit=$this->param['limit']??10;
            foreach (['bar_code','name','specs'] as $v){
                if (isset($this->param[$v])&&$this->param[$v]){
                    $where[]=[$v,'like','%'.$this->param[$v].'%'];
                }
            }
            $list=\app\home\model\MaterialDossier::with(['craftRoute','bom'])
                ->field("*")
                ->where($where)->paginate($limit);
            View::assign('list',$list);
            return table_assign(0, '', $list);
        } else {
            return \view('mx');
        }

    }
    public function removeMx()
    {
        $id=$this->param['id'];
        try {
            Db::name('production_plan_detail')->where('id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            add_log('add', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'删除失败:'.$e->getMessage());
        }
        return to_assign();
    }

    public function confirm()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $mx=Db::name('production_plan_detail')->where('status',1)->where('production_plan_id',$id)->count();
        if (!$mx){
            return to_assign(1,'请添加明细');
        }
        try {
            Db::name($this->table)->where('id',$id)->update(['confirmUser'=>$this->uid,'status'=>2,'update_time'=>time(),'confirmTime'=>time()]);
            add_log('apply', $id, $this->param,$this->title);
        }catch (\Exception $e){
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    /**
     * date:2024/4/18
     * 确认
     */
    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $mx=Db::name('production_plan_detail')->where('status',1)->where('production_plan_id',$id)->select();
        $mx=$mx->toArray()??[];
        if (!$mx){
            return to_assign(1,'请添加明细');
        }
        $ycl=Db::name('production_plan_ycl')->alias('ppy')
            ->where('ppy.status',1)
            ->leftJoin('material_dossier md','md.id=ppy.material_dossier_id')
            ->field('ppy.*,md.warehouse_id,md.warehouse_detail_id')
            ->where('ppy.production_plan_id',$id)->select();
       if (!$ycl){
           return to_assign(1,'请添加原材料明细');
       }

        Db::startTrans();
       foreach ($mx as $mxl){
           $circulationNum=dJBHBySql($this->table_detail,'printCode','LZ');
           Db::name($this->table_detail)
               ->where('id',$mxl['id'])
               ->update(['printCode'=>$circulationNum]);
       }
        try {
            $ckData=[
                'orderNum'=>'ckh',
                'type'=>'生产领料',
                'status'=>2,
                'production_plan_id'=>$id,
                'create_user'=>$this->uid,
                'out_user'=>$this->uid,
                'outTime'=>date('Y-m-d'),
                'checkTime'=>time(),
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            $ckMx=[];
            $c_data=[];
            $aa=[];
//            foreach ($mx as $ml){///算法：计划数量*额定数量*（1+损耗率）
//                $bomDetailList=Db::name('bom_detail')->where('pid',$ml['bom_id'])
//                    ->where('status','>',-1)
//                    ->select();
//                foreach ($bomDetailList as $bomDetail){
//                    $aa[]=$bomDetail['material_dossier_id'];
//                    $num=$ml['num']*$bomDetail['num']*(1+$bomDetail['loss_rate']/100);
//                    if (isset($c_data[$bomDetail['material_dossier_id']])){
//                        $c_data[$bomDetail['material_dossier_id']]+=round($num,2);
//                    }else{
//                        $c_data[$bomDetail['material_dossier_id']]=round($num,2);
//                    }
//                }
//            }
            $outId=Db::name('out_receipt')->insertGetId($ckData);
            $wId=0;
            foreach ($ycl as $key=> $cd){
//                $kucun=Db::name('material_kucun_view')->where('mdId',$key)->where('wId',1)
//                    ->find();
//                if (!$kucun){
//                    throw new Exception('库存数量不足');
//                }
//                $haveNum=(int)($kucun['countNum']-$kucun['sendNum']);
//                if ($haveNum<$cd){
//                    throw new Exception('库存数量不足'.$haveNum);
//                }
                if (!$cd['warehouse_id']){
                    throw new Exception("第 {$key} 行未找到默认仓库");
                }
                if (!$wId){
                    $wId=$cd['warehouse_id'];
                }
                $ckMx[]=[
                    'out_receipt_id'=>$outId,
                    'production_plan_id'=>$id,
                    'material_dossier_id'=>$cd['material_dossier_id'],
                    'num'=>$cd['ckNum'],
                    'status'=>2,
                    'warehouse_id'=>$cd['warehouse_id']??1,
                    'locator'=>empty($cd['warehouse_detail_id'])?1:$cd['warehouse_detail_id'],
                    'create_time'=>time(),
                    'update_time'=>time(),
                ];
            }
            Db::name('out_receipt_detail')->insertAll($ckMx);
//            $wCode=Db::connect('company')->name('warehouse')->where('id',$wId)->value('wCode');
            $ordernum=dJBHBySql('out_receipt','orderNum','A');
            Db::name('out_receipt')->where('id',$outId)->update(['orderNum'=>$ordernum]);
            $circulationNum=dJBHBySql($this->table,'circulationNum','LZ');
            Db::name($this->table)->where('id',$id)->update([
                'makeUser'=>$this->uid,
                'status'=>3,
                'circulationNum'=>$circulationNum,
                'update_time'=>time(),'checkTime'=>time()]);
            add_log('check', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }

    public function onCancel()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        Db::startTrans();
        try {
            $outStatus=Db::name('out_receipt')->where('production_plan_id',$id)->where('status','>',1)->column('status');
            if (!empty($outStatus)){
                throw new Exception('已出库不能撤回');
            }
            Db::name('out_receipt')->where('production_plan_id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            Db::name('out_receipt_detail')->where('production_plan_id',$id)->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            Db::name($this->table)->where('id',$id)->update([
                'makeUser'=>$this->uid,
                'status'=>1,
                'update_time'=>time(),
                'checkTime'=>time()]);
            add_log('check', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
    /**
     * @return \json
     * @throws \think\db\exception\DbException
     * date:2024/3/21
     * 删除
     */
    public function delete()
    {
        if (request()->isDelete()) {
            $id = get_params("id");
            $status=Db::name($this->table)->where('id','in',$id)->column('status');
            if (in_array('3',$status)){
                return  to_assign(1, "有已确认数据，不能删除");
            }
            try {
                Db::name($this->table)->where('id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('production_plan_detail')->where('production_plan_id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                Db::name('production_plan_ycl')->where('production_plan_id','in',$id)->update(['status'=>-1,'deleted'=>time()]);
                add_log('delete', $id, request()->param(),$this->title);
            }catch (\Exception $e){
                return to_assign(1, "删除失败".$e->getMessage());
            }
            return to_assign(0, "删除成功");
        } else {
            return to_assign(1, "错误的请求");
        }
    }
    public function printPage()
    {
        $id=$this->param['id']??'';
        $info=Db::name($this->table_detail)->alias('ppd')
            ->where('ppd.id',$id)
            ->join('material_dossier md','md.id=ppd.material_dossier_id','left')
            ->join('production_plan pp' ,'pp.id=ppd.production_plan_id')
            ->field("ppd.*,md.name as mdName,md.bar_code,md.specs,md.unit,pp.circulationNum,
            (select name from fy_admin a where a.id=pp.makeUser)makeUser")
            ->find();
        $mxList=Db::name('process_report_view')
            ->where('status',3)
            ->where('correlation_order',$info['production_plan_id'])
            ->where('material_dossier_id',$info['material_dossier_id'])
            ->select();
        $companyName=config('config.companyName');
        $data=[
            'companyName'=>$companyName[0],
            'orderType'=>'流转卡',
            'circulationNum'=>$info['printCode'],
            'bar_code'=>$info['bar_code'],
            'mdName'=>$info['mdName'],
            'specs'=>$info['specs'],
            'planned_time'=>$info['planned_time'],
            'num'=>$info['num'],
            'printDate'=>date('Y-m-d H:i:s'),
            'makeUser'=>$info['makeUser'],
//            'qr_code'=> "c=productionPlan&id={$info['id']}&table=".$this->table_detail. "&printCode=".$info['printCode'],
            'qr_code'=> "?printCode=".$info['printCode']."&id=".$info['id'],

        ];
        $detail=[];
        $aa=[];
        foreach ($mxList as $k=> $ml){
            $aa[$ml['craft_detail_id']][]=$ml;
//            $detail[]=[
//                'k'=>$k+1,
//                'processName'=>$ml['craftName'],
//                'qualifiedNum'=>$ml['qualifiedNum'],
//                'passNum'=>$ml['passNum'],
//                'wasteNum'=>$ml['wasteNum'],
//
//            ];
        }

        $num=0;
        foreach ($aa as $k=>$a){
            $num+=1;
            $name='';
            $qualifiedNum=0;
            $passNum=0;
            $wasteNum=0;
            foreach ($a as $a1){
                $name=$a1['craftName'];
                $qualifiedNum+=$a1['qualifiedNum'];
                $passNum+=$a1['passNum'];
                $wasteNum+=$a1['wasteNum'];
            }
                        $detail[]=[
                'k'=>$num,
                'processName'=>$name,
                'qualifiedNum'=>$qualifiedNum,
                'passNum'=>$passNum,
                'wasteNum'=>$wasteNum,

            ];
        }
        $res=[];
        foreach ($detail as $key=>$v){
            $res[$key]=$v;
        }
        $data['detail']=$res;
//        $temp='{"panels":[{"index":0,"paperType":"A4","height":297,"width":210,"paperHeader":43.5,"paperFooter":841.8897637795277,"printElements":[{"options":{"left":201,"top":21,"height":9.75,"width":220.5,"field":"companyName","testData":"重庆丰逸科技有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":246,"top":45,"height":9.75,"width":120,"field":"orderType","testData":"流转卡","fontSize":15,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":73.5,"height":9.75,"width":114,"title":"流转ID","field":"circulationNum","testData":"PROCIR1000001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":168,"top":73.5,"height":9.75,"width":132,"title":"产品编码","field":"bar_code","testData":"CPBMWLMC000001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":324,"top":73.5,"height":9.75,"width":120,"title":"产品名称","field":"mdName","testData":"物料名称0001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":30,"top":123,"height":9.75,"width":120,"title":"规格","field":"specs","testData":"产品规格001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":166.5,"top":123,"height":9.75,"width":120,"title":"计划时间","field":"planned_time","testData":"2024-01-11","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":325.5,"top":123,"height":9.75,"width":120,"title":"计划数量","field":"num","testData":"100","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":30,"top":153,"height":9.75,"width":120,"title":"工序","fontSize":10.5,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":177,"height":36,"width":550,"field":"detail","textAlign":"center","columns":[[{"title":"序号","field":"k","width":60.58261265361857,"colspan":1,"rowspan":1,"checked":true},{"title":"工序名称","field":"processName","width":140.31043946290396,"colspan":1,"rowspan":1,"checked":true},{"title":"合格品数量","field":"qualifiedNum","width":119.83988313609468,"colspan":1,"rowspan":1,"checked":true},{"title":"工废数量","field":"passNum","width":115.13888461538458,"colspan":1,"rowspan":1,"checked":true},{"title":"料废数量","field":"wasteNum","width":114.12818013199819,"colspan":1,"rowspan":1,"checked":true}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":394.5,"top":345,"height":9.75,"width":169.5,"title":"打印时间","field":"printDate","testData":"2024-02-22 22:22:22","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":396,"top":381,"height":9.75,"width":168,"title":"制单人","field":"makeUser","testData":"张二娃","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":454.5,"top":12,"height":112.5,"width":120,"field":"qr_code","testData":"13246","textType":"qrcode"},"printElementType":{"type":"text"}}],"paperNumberLeft":565,"paperNumberTop":819,"firstPaperFooter":null}]}';
        $temp='{"panels":[{"index":0,"paperType":"A4","height":297,"width":210,"paperHeader":43.5,"paperFooter":841.8897637795277,"printElements":[{"options":{"left":454.5,"top":12,"height":112.5,"width":120,"field":"qr_code","testData":"13246","textType":"qrcode"},"printElementType":{"type":"text"}},{"options":{"left":135,"top":22.5,"height":9.75,"width":307.5,"field":"companyName","testData":"重庆丰逸科技有限公司","fontSize":18,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":246,"top":45,"height":9.75,"width":120,"field":"orderType","testData":"流转卡","fontSize":15,"fontWeight":"bold","textAlign":"center"},"printElementType":{"type":"text"}},{"options":{"left":168,"top":73.5,"height":9.75,"width":132,"title":"产品编码","field":"bar_code","testData":"CPBMWLMC000001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":324,"top":73.5,"height":9.75,"width":120,"title":"产品名称","field":"mdName","testData":"物料名称0001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":28.5,"top":73.5,"height":9.75,"width":114,"title":"流转ID","field":"circulationNum","testData":"PROCIR1000001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":166.5,"top":123,"height":9.75,"width":120,"title":"计划时间","field":"planned_time","testData":"2024-01-11","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":325.5,"top":123,"height":9.75,"width":120,"title":"计划数量","field":"num","testData":"100","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":30,"top":123,"height":9.75,"width":120,"title":"规格","field":"specs","testData":"产品规格001","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":30,"top":153,"height":9.75,"width":120,"title":"工序","fontSize":10.5,"fontWeight":"bold"},"printElementType":{"type":"text"}},{"options":{"left":27,"top":177,"height":36,"width":550,"field":"detail","textAlign":"center","columns":[[{"title":"序号","field":"k","width":60.58261265361857,"colspan":1,"rowspan":1,"checked":true,"columnId":"k"},{"title":"工序名称","field":"processName","width":140.31043946290396,"colspan":1,"rowspan":1,"checked":true,"columnId":"processName"},{"title":"合格品数量","field":"qualifiedNum","width":119.83988313609468,"colspan":1,"rowspan":1,"checked":true,"columnId":"qualifiedNum"},{"title":"工废数量","field":"passNum","width":115.13888461538458,"colspan":1,"rowspan":1,"checked":true,"columnId":"passNum"},{"title":"料废数量","field":"wasteNum","width":114.1281801319982,"colspan":1,"rowspan":1,"checked":true,"columnId":"wasteNum"}]]},"printElementType":{"title":"表格","type":"tableCustom"}},{"options":{"left":394.5,"top":345,"height":9.75,"width":169.5,"title":"打印时间","field":"printDate","testData":"2024-02-22 22:22:22","fontSize":10.5},"printElementType":{"type":"text"}},{"options":{"left":396,"top":381,"height":9.75,"width":168,"title":"制单人","field":"makeUser","testData":"张二娃","fontSize":10.5},"printElementType":{"type":"text"}}],"paperNumberLeft":565,"paperNumberTop":819,"firstPaperFooter":null}]}';
        View::assign('temp',$temp);
        View::assign('info',json_encode($data,320));
        return view('../../base/view/common/print_page');
    }

    public function importData()
    {
        
    }

    public function exportData()
    {
        $where=session($this->sessionKey);
        $mStatus=['','草稿','待确认','已确认'];
        $list = Db::name('production_plan_view')
            ->where($where)
            ->field("*,
                (select sum(qualifiedNum) from fy_process_reporting  pr where pr.correlation_order=1 and pr.material_dossier_id=fy_production_plan_view.material_dossier_id and pr.status=3 and pr.is_end=1)qualifiedNum")
            ->order('production_plan_id desc')
            ->select()
            ->each(function ($item) use ($mStatus){
                $item['qualifiedNum']= $item['qualifiedNum']??0;
                $item['c_rate']=number_format(($item['qualifiedNum']/$item['num'])*100,2);
                $item['status']=$mStatus[$item['status']];
                return $item;
            });
        $title = [
            'id' => 'ID',
            'bar_code' => '物料编码',
            'mdName' => '物料名称',
            'specs' => '规格型号',
            'unit' => '单位',
            'num' => '计划数量',
            'c_rate' => '生产完成率%',
            'planned_time' => '计划时间',
            'printCode' => '流转ID',
            'orderDate' => '单据日期',
            'status' => '状态',
        ];
        $name =$this->title;
        exportXlsData($name,$title,$list);
        exit();
    }

    public function exportChaQue($id)
    {
        $list= Db::name('production_plan_ycl')->alias('ppy')
            ->where('ppy.deleted',0)
            ->where('ppy.status','>',-1)
            ->leftJoin('material_dossier md1','md1.id=ppy.material_dossier_id ')
            ->where('ppy.production_plan_id',$id)
            ->leftJoin('material_kucun_view mkv','mkv.mdId=ppy.material_dossier_id and mkv.wId=ppy.wId')
            ->field("ppy.*,mkv.mdId,mkv.bar_code,mkv.mdName,mkv.specs,mkv.unit,mkv.countNum,mkv.sendNum")
            ->select()->each(function ($item,$index){
//                $item['kcNum']=$item['countNum']-$item['sendNum'];
                $item['xh']=$index+1;
//                $item['chaque']=($item['yjNum']-$item['kcNum'])<0?0:($item['yjNum']-$item['kcNum']);
                return $item;
            })->toArray();

        $title = [
            'xh' => '序号',
            'bar_code' => '物料编码',
            'mdName' => '物料名称',
            'specs' => '规格型号',
            'unit' => '单位',
            'yjNum' => '预计数量',
            'kcNum' => '库存数量',
            'chaque' => '差缺',
        ];
        $name =$this->title.'差缺';
        exportXlsData($name,$title,$list);
        exit();
    }
}